$(function(){
	var zNodes =[];
	var getCateNode = function(){
		$.ajax({  
            async : false,  
            cache:false,  
            type: 'POST',  
            dataType : "json",  
            url: "category-list",//请求的action路径  
            error: function () {//请求失败处理函数  
                alert('请求失败');  
            },  
            success:function(data){ //请求成功后处理函数。    
            	zNodes = data;
            	$.fn.zTree.init($("#tree"), setting, zNodes);//树初始化
            	
         }  
		})
	};
	var newCount = 1;
	function addHoverDom(treeId, treeNode) {
		if(treeNode.isFirstNode){
//			return false;
		}
		var sObj = $("#" + treeNode.tId + "_span");
		if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
		var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
			+ "' title='add node' onfocus='this.blur();'></span>";
		sObj.after(addStr);
		var btn = $("#addBtn_"+treeNode.tId);
		if (btn) btn.bind("click", function(){
			var zTree = $.fn.zTree.getZTreeObj("tree");
			zTree.addNodes(treeNode, {id:(100 + newCount), pId:treeNode.id, name:"new node" + (newCount++)});
			return false;
		});
	};
	function removeHoverDom(treeId, treeNode) {
		$("#addBtn_"+treeNode.tId).unbind().remove();
	};
	function showRemoveBtn(treeId, treeNode) {
		return !treeNode.isFirstNode;
	}
	function showRenameBtn(treeId, treeNode) {
//		return !treeNode.isLastNode;
		return !treeNode.isFirstNode;
	}
	var setting = {
			data: {
				simpleData: {
					enable: true,
					idKey: "id",
					pIdKey: "pId",
					rootPId: -1
				}
			},
			view: {
				dblClickExpand: true,
				selectedMulti: false,
				showIcon: true,
				showLine: true,
				addHoverDom: addHoverDom,
				removeHoverDom: removeHoverDom
			},
			edit: {
				enable: false,
				editNameSelectAll: true,
//				showRemoveBtn: showRemoveBtn,
//				showRenameBtn: showRenameBtn
			},
			callback:{
				onClick: function(event,treeId, treeNode){
					getCateInfo(treeId, treeNode);
				}
			},
	};
	
	var getCateInfo = function(treeId, treeNode){
		$.get('get-cate-info',{'id':treeNode.id},function(data,status){
			if(status =='success' && data.Ack =='Success'){
				var Info = data.Body;
				$('#cname').val(Info.category_name);
				$('#cpid').val(Info.parent_name == null ? '根目录':Info.parent_name);
				$('#cremark').val(Info.remark);
				$('#cpid').attr('data-id',Info.parent_id);
				$('#save_cate').attr('data-id',Info.category_id);
				$('#del_cate').attr('data-id',Info.category_id);
			} else {
				if(treeNode.name != '根目录'){
					var parentNode = treeNode.getParentNode();
					$('#cname').val(treeNode.name);
					$('#cpid').val(parentNode.name == null ? '根目录':parentNode.name);
					$('#cremark').val('');
					$('#cpid').attr('data-id',(parentNode.id? parentNode.id:''));
					$('#save_cate').attr('data-id','');
					$('#del_cate').attr('data-id','');
				}
			}
		})
	}
	
	/**
	 * 获取category 数据在初始化
	 */
	getCateNode();
//	getCateInfo(treeId, treeNode);
	
	(function(){
		//初始化start
		var treeObj = $.fn.zTree.getZTreeObj("tree");
		var node = treeObj.getNodeByTId("2");//第二个
		getCateInfo('tree', node)
		//end
		/**
		 * @desc 保存数据
		 */
		$('#save_cate').on('click',function(){
			//检查是否有权限
			$.get('check-category-update',function(data,status){
				if(status =='success'){
					if(data.Error =='User authentication fails'){
						alertTips('error','你没有操作权限，如要操作，请向管理员申请！');
						return false;
					}
					$cateInfo = {
							'category_name':$('#cname').val(),
							'parent_id':$('#cpid').attr('data-id'),
							'category_id':$('#save_cate').attr('data-id'),
							'remark':$('#cremark').val(),
						}
							
					$.get('save-cate',$cateInfo,function(data,status){
						if(status=='success'){
							if(data.Ack =='Success'){
								alertTips('success','保存成功');
								setTimeout(function(){
									window.location.reload();
								},1000);
							} else if(data.Error == 'parent is not exist'){
								alertTips('error','父级类目不存在,请选保存父级类目');
								return false;
							}else{
								alertTips('error','保存失败,请重试');
								return false;
							}
						} else{
							alertTips('error','网络错误,请联系管理员!');
							return false;
						}
				 })
			  } else {
				  alertTips('error','网络错误');
				  return false;
			  }
			});
		});
		
		//删除类目
		$('#del_cate').on('click',function(){
			$.get('check-category-del',function(data,status){
				if(status =='success'){
					if(+data){
						var nodes = treeObj.getSelectedNodes();
						var did = $('#del_cate').attr('data-id');
						if(nodes[0].isParent){
							if(confirm('删除该类目，下属的类目也会删除，是否继续')){
								delCate(did);
							} else {
								return false;
							}
						} else {
							if(confirm('是否删除该类目')){
								delCate(did);
							} else {
								return false;
							}
						}
					} else{
						alertTips('error','你没有操作权限，如要操作，请向管理员申请！');
						return false;
					}
				}else {
					  alertTips('error','网络错误');
					  return false;
				}
			})
		})
	})()
	
	var delCate = function(id){
		$.get('del-cate',{'id':id},function(data,status){
			if(status=='success'){
				if(data.Ack =='Success'){
					alertTips('success','删除成功');
					setTimeout(function(){
						window.location.reload();
					},1000);
				} else{
					alertTips('error','删除失败,请重试');
					return false;
				}
			} else{
				alertTips('error','网络错误,请联系管理员!');
				return false;
			}
		});
	}
})